﻿/**************************************************************
 *
 * 唯一标识：9f642a1d-fb12-4629-ad99-5182698aaba9
 * 命名空间：Sgr.Tests
 * 创建时间：2024/7/21 19:35:01
 * 机器名称：DESKTOP-HJ4OAG9
 * 创建者：CocoYuan
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：
 *
 **************************************************************/

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;

namespace Sgr.Tests
{
    public class SgrBaseTestFixture : IDisposable
    {
        private volatile bool _disposedValue;
        private readonly TestServer _testServer;

        public TestServer Server
        {
            get
            {
                return _testServer;
            }
        }

        public IServiceProvider ServiceProvider => _testServer.Services;

        public SgrBaseTestFixture()
        {
            _testServer = CreateTestServer();
            InitTestData();
        }

        protected virtual TestServer CreateTestServer()
        {
            return new TestServer(CreateWebHostBuilder());
        }

        protected virtual IWebHostBuilder CreateWebHostBuilder()
        {
            var builder = WebHost.CreateDefaultBuilder();

            ConfigureWebHost(builder);

            return builder;
        }

        protected virtual void ConfigureWebHost(IWebHostBuilder builder)
        {
        }

        protected virtual void InitTestData()
        {
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposedValue)
            {
                if (disposing)
                {
                    _testServer.Dispose();
                }

                _disposedValue = true;
            }
        }

        public void Dispose()
        {
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }
    }
}